import Vue from "vue"
import VueRouter from "vue-router"
Vue.use(VueRouter)   // 全局注册插件 

// 1. 创建路由组件    @ === src 别名 alias 
import Login from "@/views/Login.vue"

import StuRouter from "@/views/student/router";
import TeacherRouter from "@/views/teacher/router"

import {MessageBox} from "element-ui"
// 2. 路由对象
const routes = [
    {
        path:"/",
        redirect:"/login"
    },
    {
        path:"/login",
        name:"login",
        component:Login
    },
    {
        path:"/main",
        name:'main',
        component:()=>import('@/views/Main.vue'),
        children:[
            ...StuRouter,
            ...TeacherRouter,
        ]
    },
    {
        path:"*",
        redirect:"/login"
    }
]
// 3. 路由实例化
const router = new VueRouter({
  routes,
  mode:"hash"
})

function showAlert(){
    MessageBox.alert("你暂无访问权限...","警告",{
        confirmButtonText: '确定',
        type:"warning",
        callback: action => {
            router.push({name:"login"})
        }
    })
}

router.beforeEach((to,from,next)=>{
    // console.log(to);

    if(localStorage.rolltype=="2"){
        // 教师身份 
        if(to.name.indexOf("stu")>-1){
            showAlert()
        }else{
            next()
        }
    }
    
    if(localStorage.rolltype=="1"){
        if(to.name.indexOf("teacher")>-1){
            showAlert();
        }else{
            next()
        }
    }

    next();
})

const originalPush = VueRouter.prototype.push
   VueRouter.prototype.push = function push(location) {
   return originalPush.call(this, location).catch(err => err)
}

// 4. 挂载到根实例
export default router;

// 5. 路由出口 